package com.leyou.cart.service;


import com.leyou.cart.entity.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:user:";

    public void addItemToCart(Cart cart) {
        //获取当前用户
        Long userid = UserHolder.getUser();
        String key = KEY_PREFIX + userid;
        //获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        addCartInRedis(cart, hashOps);


    }

    private void addCartInRedis(Cart cart, BoundHashOperations<String, String, String> hashOps) {
        //获取商品Id作为hashkey
        String hashKey = cart.getSkuId().toString();
        //判断是否存在
        Boolean boo = hashOps.hasKey(hashKey);
        if (boo != null && boo){
            //存在，先取出来
            String json = hashOps.get(hashKey);
            Cart cacheCart = JsonUtils.toBean(json, Cart.class);
            //修改数量
            cart.setNum(cacheCart.getNum() + cart.getNum());
            //写入redis
            hashOps.put(hashKey,JsonUtils.toString(cacheCart));
        }
        //写入redis
        hashOps.put(hashKey,JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        //获取用户信息
        Long userId = UserHolder.getUser();
        String key = KEY_PREFIX + userId;
        //判断是否存在
        Boolean boo = redisTemplate.hasKey(key);
        if (boo == null || !boo){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        List<String> values = hashOps.values();
        if (CollectionUtils.isEmpty(values)){
            //不存在返回404
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 查询购物车数据
        return hashOps.values().stream().map(json -> JsonUtils.toBean(json,Cart.class)).collect(Collectors.toList());
    }

    public void updateCart(Long id, Integer num) {
        //获取用户信息
        Long userid = UserHolder.getUser();
        String key = KEY_PREFIX + userid;
        //获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);

        String skuId = id.toString();
        Boolean boo = hashOps.hasKey(skuId);
        if (boo ==null || !boo){
            log.error("购物车商品不存在，用户：{}, 商品：{}", userid, id);
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //查询购物车商品
        Cart cart = JsonUtils.toBean((String) hashOps.get(skuId),Cart.class);
        //修改数量
        cart.setNum(num);
        //写回redis
        hashOps.put(skuId,JsonUtils.toString(cart));
    }

    public void deleteCart(String skuId) {
        //获取用户信息
        Long userid = UserHolder.getUser();
        String key = KEY_PREFIX + userid;
        //获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        hashOps.delete(skuId);


    }

    public void addItemToCarts(List<Cart> carts) {
        //获取当前用户
        Long userid = UserHolder.getUser();
        String key = KEY_PREFIX + userid;
        //获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        for (Cart cart : carts) {
        addCartInRedis(cart, hashOps);

        }
    }
}
